from sqlalchemy.orm import Session
from schema import Farm_Admin_schema
from model import Farm_Admin_model



def get_Farm_Admin(db: Session, ID: int):
    return db.query(Farm_Admin_model.Farm_admin).filter(Farm_Admin_model.Farm_admin.ID == ID).first()


def get_all_Farm_Admin(db: Session):
    return db.query(Farm_Admin_model.Farm_admin).all()


def delete_Farm_Admin(db: Session, ID):
    to_delete = db.query(Farm_Admin_model.Farm_admin).filter(Farm_Admin_model.Farm_admin.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Farm_Admin(db: Session, Farm_Admin: Farm_Admin_schema.Farm_admin):
    db_Farm_Admin = Farm_Admin_model.Farm_admin(
        Account=Farm_Admin.Account,
        Name=Farm_Admin.Name,
        Password=Farm_Admin.Password,
        Phone=Farm_Admin.Phone,
        Email=Farm_Admin.Email,
    )
    db.add(db_Farm_Admin)
    db.commit()
    db.refresh(db_Farm_Admin)
    return db_Farm_Admin


def update_Farm_Admin(db: Session, ID, field_name, new_value):
    db_Farm_Admin = db.query(Farm_Admin_model.Farm_admin).filter(Farm_Admin_model.Farm_admin.ID == ID).first()
    setattr(db_Farm_Admin, field_name, new_value)
    db.commit()
    db.refresh(db_Farm_Admin)
    return db_Farm_Admin
